from django.db.models import Q
from django.shortcuts import render
from rest_framework import request,status
from rest_framework.views import APIView,Response

from myapp.views import MyPagination
from utils.jwt_token import check_token
from utils.log import create_log
from utils.force_login import check_login
from myapp.models import *
from utils.login_util import operation_log
from .serializer import *
import datetime

# 获取流程实例
class ProcessAPIView(APIView):
    queryset = ProcessInsModel.objects.filter(logic_del=0).all()
    serializer_class = ProcessSer
    pagination_class = MyPagination


# 获取单个流程实列
class ProcessAPI(APIView):
    @check_login
    def get(self,request,pk):
        process = ProcessInsModel.objects.get(id=pk)
        process_ser = ProcessSer(process).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': process_ser})

    @check_login
    def delete(self,request,pk):
        process = ProcessInsModel.objects.get(id=pk)
        if process.state == 0:
            ProcessInsModel.objects.filter(id=pk).update(state=4)
            operation_log(request, '撤销了一个事项')
            return Response({'code':status.HTTP_200_OK,'msg':'撤销成功'})
        else:
            return Response({'code':status.HTTP_400_BAD_REQUEST,'msg':'撤销失败，正在审批中'})

# 模糊查询流程实例
class ProcessVague(APIView):
    @check_login
    def post(self, request):
        user = request.data.get('user')
        apply = request.data.get('apply')
        state = request.data.get('state')
        if state == '未审批':
            state =0
        elif state =='审批中':
            state =1
        elif state =='通过':
            state = 2
        elif state =='驳回':
            state = 3
        elif state =='撤销':
            state =4
        print(user, apply, state)
        try:
            user = UserModel.objects.filter(username__contains=user).first()
        except Exception as e:
            print(e)
        try:
            apply = ApplyTypeModel.objects.filter(name__contains=apply).first()
        except Exception as e:
            print(e)
        a = ''
        b=''
        c=''
        if user:
            a = user.id
        elif apply:
                b = apply.id
        elif state:
            c = state
        search_dict = {}
        if a:
            search_dict['user'] = a
        else:
            search_dict['user'] = ""
        if b:
            search_dict['apply'] = b
        else:
            search_dict['apply'] = ""
        if c:
            search_dict['state'] = c
        else:
            search_dict['state'] = ""
        print(search_dict)
        user = ProcessInsModel.objects.filter(user__id__contains=search_dict['user']) \
            .filter(apply__id__contains=search_dict['apply']) \
            .filter(state__contains=search_dict['state'])
        user_ser = ProcessSer(user, many=True).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': user_ser})

# 通过申请类型id获取审批流程接口
class ApproverAPIView(APIView):
    def get(self,reqeust,pk):
        approver = ApproverModel.objects.filter(apply_id = pk).all()
        approver_ser = ApproverSer(approver,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':approver_ser})

# 代办事项
class UserProcessAPIView(APIView):
    @check_login
    def get(self,request):
        user = request.session.get('user')
        uid = user['user_id']
        process = ProcessInsModel.objects.filter(approver_id=uid,state=0).all()
        process_ser =ProcessSer(process,many=True).data
        return Response({'code':status.HTTP_200_OK,'msg':'获取成功','data':process_ser})

# 单个代办事项
class UserPorcessAPI(APIView):
    @check_login
    def get(self, request, pk):
        process = ProcessInsModel.objects.get(id=pk)
        process_ser = ProcessSer(process).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': process_ser})

    @check_login
    def put(self,request,pk):
        user = request.session.get('user')
        uid = user['user_id']
        comment = request.data.get('comment')
        crea =datetime.datetime.now()
        ProcessInsModel.objects.filter(id=pk).update(state=3)
        NodeModel.objects.create(process_id=pk,user_id=uid,comment=comment,state=3,times=crea)
        operation_log(request, '驳回了一个代办事项')
        return Response({'code':status.HTTP_200_OK,'msg':'驳回成功'})

# 同意
class UserPorcess(APIView):
    @check_login
    def put(self, request, pk):
        user = request.session.get('user')
        uid = user['user_id']
        comment = request.data.get('comment')
        crea = datetime.datetime.now()
        ProcessInsModel.objects.filter(id=pk).update(state=2)
        NodeModel.objects.create(process_id=pk, user_id=uid, comment=comment, state=2, times=crea)
        operation_log(request, '同意了一个事项')
        return Response({'code': status.HTTP_200_OK, 'msg': '通过成功'})

# 模糊查询代办事项
class UserProcessVague(APIView):
    @check_login
    def post(self, request):
        user = request.session.get('user')
        uid = user['user_id']
        user = request.data.get('user')
        apply = request.data.get('apply')
        state = request.data.get('state')
        if state == '未审批':
            state =0
        elif state =='审批中':
            state =1
        elif state =='通过':
            state = 2
        elif state =='驳回':
            state = 3
        elif state =='撤销':
            state =4
        print(user, apply, state)
        try:
            user = UserModel.objects.filter(username__contains=user).first()
        except Exception as e:
            print(e)
        try:
            apply = ApplyTypeModel.objects.filter(name__contains=apply).first()
        except Exception as e:
            print(e)
        a = ''
        b=''
        c=''
        if user:
            a = user.id
        elif apply:
                b = apply.id
        elif state:
            c = state
        search_dict = {}
        if a:
            search_dict['user'] = a
        else:
            search_dict['user'] = ""
        if b:
            search_dict['apply'] = b
        else:
            search_dict['apply'] = ""
        if c:
            search_dict['state'] = c
        else:
            search_dict['state'] = ""
        print(search_dict)
        user = ProcessInsModel.objects.filter(user__id__contains=search_dict['user'],approver=uid) \
            .filter(apply__id__contains=search_dict['apply'],approver=uid) \
            .filter(state__contains=search_dict['state'],approver=uid)
        user_ser = ProcessSer(user, many=True).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': user_ser})

# 已办事项
class UserProcessFinished(APIView):
    @check_login
    def get(self,request):
        user = request.session.get('user')
        uid = user['user_id']
        process = ProcessInsModel.objects.filter(approver_id=uid, state=2).all()
        process_ser = ProcessSer(process, many=True).data
        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': process_ser})

# 单个已办事项
class UserProcessFinishedAPI(APIView):
    @check_login
    def get(self, request, pk):
        process = ProcessInsModel.objects.get(id=pk)
        process_ser = ProcessSer(process).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': process_ser})


# 模糊查询已办事项
class UserProcessFinishedVague(APIView):
    @check_login
    def post(self, request):
        user = request.session.get('user')
        uid = user['user_id']
        user = request.data.get('user')
        apply = request.data.get('apply')
        state = request.data.get('state')
        if state == '未审批':
            state =0
        elif state =='审批中':
            state =1
        elif state =='通过':
            state = 2
        elif state =='驳回':
            state = 3
        elif state =='撤销':
            state =4
        print(user, apply, state)
        try:
            user = UserModel.objects.filter(username__contains=user).first()
        except Exception as e:
            print(e)
        try:
            apply = ApplyTypeModel.objects.filter(name__contains=apply).first()
        except Exception as e:
            print(e)
        a = ''
        b=''
        c=''
        if user:
            a = user.id
        elif apply:
                b = apply.id
        elif state:
            c = state
        search_dict = {}
        if a:
            search_dict['user'] = a
        else:
            search_dict['user'] = ""
        if b:
            search_dict['apply'] = b
        else:
            search_dict['apply'] = ""
        if c:
            search_dict['state'] = c
        else:
            search_dict['state'] = ""
        print(search_dict)
        user = ProcessInsModel.objects.filter(user__id__contains=search_dict['user'],approver=uid) \
            .filter(apply__id__contains=search_dict['apply'],approver=uid) \
            .filter(state__contains=search_dict['state'],approver=uid)
        user_ser = ProcessSer(user, many=True).data

        return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': user_ser})


# 请假
class LeaveViews(APIView):
    def get(self, request):
        # 反向查询请假的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=1).all()
        cate_ser = ApplyCategorySer(cate, many=True).data
        flow = FlowModel.objects.filter(id=1).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        start_times = request.data.get('start_times')  # 获取请假开始的时间
        end_times = request.data.get('end_times')  # 获取请假结束时的时间
        cause = request.data.get('cause')  # 请假原因
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id
            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)
            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)

        '''
        开始写入请假模板, 并且绑定实例id
        '''
        try:
            LeaveModel.objects.create(process_id=process.id, start_time=start_times, end_time=end_times, cause=cause)
        except Exception as e:
            print('写入申请模板的报错信息是', e)

        create_log(request, '请假申请')

        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})

# 借车申请
class CarViews(APIView):
    def get(self, request):
        # 反向查询借车的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=2).all()
        cate_ser = []

        for i in cate:
            data = {'id': i.id, 'car_tpye': i.leaves_type}
            # 反向查询获取所有的车牌号
            number = CarNumberModel.objects.filter(cate_id=i.id).all()
            number_list = []
            for j in number:
                data_ = {'id': j.id, 'name': j.car_number}
                number_list.append(data_)
            data['car_number'] = number_list
            cate_ser.append(data)
        flow = FlowModel.objects.filter(id=2).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        start_times = request.data.get('start_times')  # 获取请假开始的时间
        end_times = request.data.get('end_times')  # 获取请假结束时的时间
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id
        car_number = request.data.get('car_number')  # 获取车牌号id
        start_address = request.data.get('start_address')  # 起始地
        end_address = request.data.get('end_address')  # 目的地

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id

            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)

            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)

        '''
        开始写入模板, 并且绑定实例id
        '''
        try:
            CarModel.objects.create(process_id=process.id, start_time=start_times, end_time=end_times,
                                    start_address=start_address, end_address=end_address, car_number_id=car_number)
        except Exception as e:
            print('写入申请模板的报错信息是', e)
        create_log(request, '借车申请')
        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})

# 出差申请
class EvectionViews(APIView):
    def get(self, request):
        # 反向查询出差的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=3).all()
        cate_ser = ApplyCategorySer(cate, many=True).data
        flow = FlowModel.objects.filter(id=3).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        start_times = request.data.get('start_times')  # 获取开始的时间
        end_times = request.data.get('end_times')  # 获取结束时的时间
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id
        cause = request.data.get('cause')  # 出差原因
        address = request.data.get('address')  # 目的地
        together = request.data.get('together')  # 同行人

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id
            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)

            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)

        '''
        开始写入模板, 并且绑定实例id
        '''
        try:
            EvectionModel.objects.create(process_id=process.id, start_time=start_times, end_time=end_times,
                                         address=address, cause=cause, together=together)
        except Exception as e:
            print('写入申请模板的报错信息是', e)
        create_log(request, '出差申请')
        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})

# 借款申请
class BorrowViews(APIView):
    def get(self, request):
        # 反向查询出差的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=4).all()
        cate_ser = ApplyCategorySer(cate, many=True).data
        flow = FlowModel.objects.filter(id=4).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        start_times = request.data.get('start_times')  # 获取开始的时间
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id
        cause = request.data.get('cause')  # 原因
        amount = request.data.get('amount')  # 借款金额的数量

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id
            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)

            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)

        '''
        开始写入模板, 并且绑定实例id
        '''
        try:
            BorrowModel.objects.create(process_id=process.id, start_time=start_times, amount=amount,
                                       cause=cause)
        except Exception as e:
            print('写入申请模板的报错信息是', e)
        create_log(request, '借款申请')
        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})

# 转正申请
class FormalViews(APIView):
    def get(self, request):
        # 反向查询出差的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=5).all()
        cate_ser = ApplyCategorySer(cate, many=True).data
        flow = FlowModel.objects.filter(id=5).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        start_times = request.data.get('start_times')  # 获取开始的时间
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id
        cause = request.data.get('cause')  # 原因

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id
            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)

            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)

        '''
        开始写入模板, 并且绑定实例id
        '''
        try:
            FormalModel.objects.create(process_id=process.id, start_time=start_times, cause=cause)
        except Exception as e:
            print('写入申请模板的报错信息是', e)
        create_log(request, '转正申请')
        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})

# 报销申请
class SubmitViews(APIView):
    def get(self, request):
        # 反向查询出差的分类
        cate = ApplyCategoryModel.objects.filter(apply_id=6).all()
        cate_ser = ApplyCategorySer(cate, many=True).data
        flow = FlowModel.objects.filter(id=6).first()
        return Response({'msg': '获取成功', 'code': status.HTTP_200_OK, 'state': flow.state, 'data': cate_ser})

    def post(self, request):
        apply_id = request.data.get('apply_id')  # 获取申请分类的id
        amount = request.data.get('amount')  # 获取报销金额
        times = request.data.get('times')  # 什么时候申请的
        apply = request.data.get('apply')  # 获取申请类型的id
        cause = request.data.get('cause')  # 原因
        print('金额', amount, '类型', type(amount))

        token = request.headers.get('Authorization')
        payload = check_token(token)
        user_id = payload['user_id']

        if FlowModel.objects.filter(id=apply, state=0).first():
            return Response({'msg': '流程被禁用', 'code': status.HTTP_400_BAD_REQUEST})

        '''
        根据申请类型获取审批的角色
        先写入实例模板
        '''
        try:
            approver = ApproverModel.objects.filter(apply_id=apply).all()
            user = UserModel.objects.filter(id=user_id).first()
            users = []  # 审批的角色的id
            for i in approver:
                username = UserModel.objects.filter(department_id=user.department.id, role_id=i.role_id).first()
                users.append(username.id)
            print(users)

            process = ProcessInsModel.objects.create(user_id=user_id, apply_id=apply_id, times=times,
                                                     approver_id=users[0])
        except Exception as e:
            print('申请写入实例模板的报错信息', e)

        '''
        开始写入审批节点表
        '''
        try:
            NodeModel.objects.create(user_id=users[0], process_id=process.id, state=1)
            for i in users[1:]:
                NodeModel.objects.create(user_id=i, process_id=process.id)
        except Exception as e:
            print('写入审批节点的报错信息是', e)
        '''
        开始写入模板, 并且绑定实例id
        '''
        try:
            SubmitModel.objects.create(process_id=process.id, cause=cause, amount=amount)
        except Exception as e:
            print('写入申请模板的报错信息是', e)
        create_log(request, '报销申请')
        return Response({'msg': '申请成功', 'code': status.HTTP_200_OK})
